<template>
  <div>
    <div style="padding-left: 30px;padding-right: 30px">
      <el-form :inline="true" :model="roleDto" class="demo-form-inline">

        <el-row :gutter="20">
          <el-col :span="8">
            <!--输入框-->
            <el-form-item label="编码：">
              <el-input v-model="roleDto.code" placeholder="编码"></el-input>
            </el-form-item>
          </el-col>
          <!--       当前地区 -->
          <el-col :span="8">
            <el-form-item label="角色名称：">
              <el-input v-model="roleDto.name" placeholder="角色名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <!--        date-->
            <el-date-picker
              v-model="value1"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item>
              <el-button type="primary" @click="page">查询</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
    </el-row>

    <!--    添加修改-->
    <div>
      <el-dialog :title="addpud==true?'添加角色':'修改角色'" :visible.sync="outerVisible" class="custom-dialog">
        <el-form ref="form" :model="role" label-width="80px">

          <el-form-item label="角色名称:">
            <el-input v-model="role.name"></el-input>
          </el-form-item>
          <el-form-item label="角色编码:">
            <el-input v-model="role.code"></el-input>
          </el-form-item>
          <el-form-item label="内置角色:">
            <el-radio-group v-model="role.readonly">
              <el-radio label="1" value="1">是</el-radio>
              <el-radio label="0" value="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="状态：">
            <el-radio-group v-model="role.status">
              <el-radio label="1" value="1">启用</el-radio>
              <el-radio label="0" value="0">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="功能描述:">
            <el-input v-model="role.describe" type="textarea" placeholder="请输入内容"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="add2" v-if="addpud">新增</el-button>
            <el-button type="warning" @click="upd2" v-if="addpud==false">修改</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
    <div>
      <!--      表格显示-->
      <el-table :data="Data" border style="width: 100%" ref="multipleTable" @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          width="55"
        >
        </el-table-column>
        <el-table-column
          prop="code"
          label="角色编码"
          width="100"
        ></el-table-column>
        <el-table-column
          prop="name"
          label="角色名称"
        ></el-table-column>
        <el-table-column
          prop="readonly"
          label="是否内置角色"
          sortable
          width="180"
          column-key="date"
          :filters="[{text: '是', value:1}, {text: '否', value:0}]"
          :filter-method="filterHandler"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.readonly" style="color: #00afff">是</span>
            <span v-else style="color: red">否</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          sortable
          width="180"
          column-key="date"
          :filters="[{text: '正常', value:1}, {text: '异常', value:0}]"
          :filter-method="filterHandler"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.status" style="color: #00afff">正常</span>
            <span v-else style="color: red">异常</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="describe"
          label="描述"
        ></el-table-column>

        <el-table-column label="操作" width="150">
          <template slot-scope="scope">

            <el-button slot="reference" size="mini"
                       type="text"
                       @click="del(scope.row.id)"
            >删除
            </el-button>
            <el-button slot="reference" size="mini"
                       type="text"
                       @click="upd(scope.row)"
            >修改
            </el-button>

            <el-dropdown @command="handleCommand" size="mini">
              <span class="el-dropdown-link">
                更多<i class="el-icon-ar  row-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="handleDataScope" icon="el-icon-circle-check" :id="scope.row">数据权限</el-dropdown-item>
                <el-dropdown-item command="handleAuthUser" icon="el-icon-user" :id="scope.row">分配用户</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>

          </template>
        </el-table-column>
      </el-table>

      <el-dialog title="角色授予菜单" :visible.sync="outerVisible2" class="custom-dialog" @close="handleDialogClose">
        <div>
          <el-row>
            <el-col :span="12">
              <span>当前角色：</span>
              <span style="color: #7a6df0; font-size: 20px">{{ rolename }}</span>
            </el-col>
            <el-col :span="12">
              <el-button type="success" round @click="menu2">授予菜单</el-button>
            </el-col>
          </el-row>

        </div>
        <div></div>
        <div>
          <el-row>
            <el-col :span="12">
              <h2>菜单列表</h2>
              <el-divider></el-divider>

              <div style="max-height:600px; overflow-y: auto; margin: 20px 0;">
                <el-tree
                  class="tree-border"
                  :data="menuLists"
                  show-checkbox
                  default-expand-all
                  ref="dept"
                  node-key="id"
                  empty-text="加载中，请稍候"
                  v-model="checkedMenuIds"
                  @node-click="handleNodeClick"
                  :props="defaultProps"
                  :check-strictly="true"
                ></el-tree>
              </div>
            </el-col>
            <el-col :span="12">
              <h2>权限配置</h2>
              <el-divider></el-divider>
              <div style="max-height:600px; overflow-y: auto; margin: 20px 0;">
                <el-tree
                  class="tree-border"
                  :data="authRole"
                  show-checkbox
                  default-expand-all
                  ref="authRole"
                  node-key="id"
                  empty-text=无配置
                  v-model="authroleId"
                  :props="defaultProp"
                  :check-strictly="true"
                ></el-tree>
              </div>
            </el-col>

          </el-row>

        </div>
      </el-dialog>

      <el-pagination
        @size-change="roleDto.pageSize"
        @current-change="curren"
        :current-page="roleDto.pageNum"
        :page-sizes="[5, 10, 20, 30]"
        :page-size=this.roleDto.pageSize
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>


<!--      分配用户-->
      <el-dialog title="分配用户" :visible.sync="outerVisible3" class="custom-dialog" @close="handleDialogClose2">
        <div>
          <el-row>
            <el-col :span="12">
              <span>当前角色：</span>
              <span style="color: #7a6df0; font-size: 20px">{{ rolename }}</span>
            </el-col>
            <el-col :span="12">
              <el-button type="success" round @click="user2">分配用户</el-button>
            </el-col>
          </el-row>

        </div>
        <div></div>
        <div>
          <el-row>
            <el-col :span="12">
              <h2>组织列表</h2>
              <el-divider></el-divider>

              <div style="max-height:600px; overflow-y: auto; margin: 20px 0;">
                <el-tree
                  class="tree-border"
                  :data="orglist"
                  default-expand-all
                  ref="dept"
                  node-key="id"
                  empty-text="加载中，请稍候"
                  @node-click="handleNodeClick2"
                  :props="defaultProps"
                ></el-tree>
              </div>
            </el-col>
            <el-col :span="12">
              <h2>用户列表</h2>
              <el-divider></el-divider>
              <div style="max-height:600px; overflow-y: auto; margin: 20px 0;">
                <el-tree
                  class="tree-border"
                  :data="userRole"
                  show-checkbox
                  default-expand-all
                  ref="userRole"
                  node-key="id"
                  empty-text=无配置
                  v-model="userroleId"
                  :props="defaultProp"
                  :check-strictly="true"
                ></el-tree>
              </div>
            </el-col>

          </el-row>

        </div>
      </el-dialog>
    </div>
  </div>

</template>

<script>
import {
  addRole,
  addRoleMenu,
  delRole,
  listAllByMenuId,
  listRoleMenu,
  menuVos,
  pageRole,
  updRole,
  listAllByRoleId,
  saveRoleAuthority,
  selectOrg,
  lists,
  userRoleId,
  addUserRole2
} from '@/api/pd-auth/role.js'
import IconSelect from '@/components/IconSelect/index.vue'
import Treeselect from '@riophae/vue-treeselect'
import user from '@/store/modules/user'
import authRole from '@/views/system/user/authRole.vue'

export default {
  components: { Treeselect, IconSelect },
  data() {
    return {
      xxx: [],//上一次点击的用户数组
      weww: [],
      bbbb:[],//点击上一次
      aaaas:false,
      aas:false,
      authRoleDto:{
        roleId: '',
        authorityIdList: [],
        authorityType:'RESOURCE',
        create_user:""
      },
      authRole:[],//权限配置
      ahthrolidss:"",//点击的角色id
      authroleId:[],//原有的角色权限id
      userroleId:[],//原有的角色用户id
      userRole:[],//对应的用户集合
      rolename: '',
      roleId: '',
      user: user.state,
      outerVisible: false,
      outerVisible2: false,
      outerVisible3: false,//分配用户对话狂
      addpud: true,
      checkedMenuIds: [],
      menuIds: [],//没有选择的值
      menuLists: [],
      orglist:[],//组织
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      form: {},
      defaultProps: {
        children: 'list',
        label: 'name'
      },
      defaultProp: {
        label: 'name'
      },
      value2: '',
      value1: [],
      roleMenuDto: {
        roleId: '',
        menuIds: []
      },
      role: {
        id: '',
        name: '',
        code: '',
        status: '1',
        describe: '',
        readonly: '0',//是否内置角色
        create_time: '',
        create_user: '',
        update_time: '',
        update_user: ''
      },
      userDto:{
        org_id:null
      },
      userDto2:{
        role_id:null,
      },
      userRoleDto:{
        uids:[],
        roleid:null,
        cuid:null,
      },
      roleDto: {
        name: '',
        code: '',
        create_time: '',
        out_time: '',
        pageNum: 1,
        pageSize: 5
      },
      title: '',
      Data: [],
      total: 0,
      name:"设置",
      count:0
    }
  },

  //创建生命周期树
  created() {
    this.page()
  },

  methods: {
//分配用户对话框关闭
    handleDialogClose2(action) {
      this.aas=false
      this.userRole=[]
      this.userroleId=[]
      // console.log("sss")
      // 在这里处理对话框关闭事件
    },

    handleDialogClose(action) {
      this.aaaas=false
      this.authRole=[]
     // console.log("sss")
      // 在这里处理对话框关闭事件
    },

    handleCommand(command,id) {
      // 处理下拉菜单命令
      if (command === 'handleDataScope') {
        this.ahthrolidss=id.$attrs.id.id
        this.menu(id.$attrs.id)
        // 处理数据权限命令
      } else if (command === 'handleAuthUser') {
        this.rolename = id.$attrs.id.name
        this.ahthrolidss = id.$attrs.id.id
        selectOrg().then(as=>{
          this.orglist=as
        })

        this.userDto2.role_id=this.ahthrolidss
        userRoleId(this.userDto2).then(ew=>{
          this.userroleId=ew
          console.log("当前角色的",ew)
        })
        this.outerVisible3= true
        // 处理分配用户命令
      }
    },


    //点击授予菜单
    menu(val) {
      this.outerVisible2 = true
      this.rolename = val.name
      this.roleMenuDto.roleId = val.id
      this.ahthrolidss = val.id
      //查询当前角色的菜单
      listRoleMenu(val.id).then(as => {
        this.checkedMenuIds = as.data
        this.$refs.dept.setCheckedKeys(this.checkedMenuIds)
      })
    },

    //分配角色对话框关闭
    user2() {
      this.outerVisible3 = false
      this.userRoleDto.cuid=this.user.id
      this.userRoleDto.uids=this.userroleId
      this.userRoleDto.roleid=this.ahthrolidss
      addUserRole2(this.userRoleDto).then(ew=>{
        this.userroleId=[]
        this.$message({
          type: 'success',
          message: '分配用户成功!'
        })
      })
      // console.log("sss")
      // 在这里处理对话框关闭事件
    },

    //点击菜单
    handleNodeClick(data){
      listAllByMenuId(data.id).then(as => {
        this.authRole = as.data
        if (this.aaaas){
          //选中
          const checkedNodes2 = this.$refs.authRole.getCheckedNodes(true)//选中的权限配置
          const xz= checkedNodes2.map(node => node.id)
          // 检查第二个数组中第一个数组没有的值，并添加到第一个数组中
          xz.forEach(item => {
            if (!this.authroleId.includes(item)) {
              this.authroleId.push(item);
            }
          });
          for (let i = 0; i <this.weww.length; i++) {

              if (!xz.includes(this.weww[i]) && this.authroleId.includes(this.weww[i])) {
                // 找到需要删除的元素在 this.authroleId 中的索引
                const index = this.authroleId.indexOf(this.weww[i]);
                if (index !== -1) {
                  // 直接在原数组中删除该元素
                  this.authroleId.splice(index, 1);

              }
            }
          }
      }

        this.weww=this.authRole.map(node => node.id)


        //查询当前角色的权限
        listAllByRoleId(this.ahthrolidss).then(ews=>{
          if (!this.aaaas){
            this.aaaas=true
          }
          this.bbbb=ews.data
          this.bbbb.forEach(item => {
            if (!this.authroleId.includes(item)) {
              this.authroleId.push(item);
            }
          });
          this.$refs.authRole.setCheckedKeys(this.authroleId)
        })


      })
    },

    //点击组织
    handleNodeClick2(data) {
      if (this.aas){
        //选中
        this.xxx=this.userRole.map(node => node.id)
        console.log("syc",this.xxx)
        console.log("将来")
        const checkedNodes2 = this.$refs.userRole.getCheckedNodes(true)//选中的权限配置
        const xz= checkedNodes2.map(node => node.id)
        // 检查第二个数组中第一个数组没有的值，并添加到第一个数组中
        xz.forEach(item => {
          if (!this.userroleId.includes(item)) {
            this.userroleId.push(item);
          }
        });

        for (let i = 0; i <this.xxx.length; i++) {
            if (!xz.includes(this.xxx[i]) && this.userroleId.includes(this.xxx[i])) {
              // 找到需要删除的元素在 this.authroleId 中的索引
              const index = this.userroleId.indexOf(this.xxx[i]);
              if (index !== -1) {
                // 直接在原数组中删除该元素
                this.userroleId.splice(index, 1);
              }
            }
          }
      }
      //点击上一次的用户id

      //根据id查询对应用户
      this.userDto.org_id=data.id
      lists(this.userDto).then(as=>{
        this.userRole=as
        this.$refs.userRole.setCheckedKeys(this.userroleId)
      })


      if (!this.aas){
        this.aas=true
      }
    },

    menu2() {
      const checkedNodes = this.$refs.dept.getCheckedNodes(true)//选中的菜单
      this.roleMenuDto.menuIds=checkedNodes.map(node => node.id)

      this.authRoleDto.authorityIdList = this.authroleId
        //授予菜单
      addRoleMenu(this.roleMenuDto).then(as => {
        this.$message({
          type: 'success',
          message: '授予菜单成功!'
        })
      })
      this.authRoleDto.create_user=this.user.id
      this.authRoleDto.roleId=this.ahthrolidss
      //配置权限设置
      saveRoleAuthority(this.authRoleDto).then(as => {
        this.authRole=[]
        this.$message({
          type: 'success',
          message: '配置权限成功!'
        })
      })

      this.outerVisible2 = false
    },

    //状态
    filterHandler(value, row, column) {
      const property = column['property']
      return row[property] === value
    },

    //添加
    add2() {
      this.role.create_user = this.user.id
      this.role.update_user = this.user.id
      console.log(this.role)
      addRole(this.role).then(as => {
        this.role = {}
        this.role.status = '1'
        this.role.readonly = '0'
        this.outerVisible = false
        this.page()
      })
      this.$message({
        type: 'success',
        message: '添加成功!'
      })
    },
    //修改
    upd2() {
      updRole(this.role).then(as => {
        this.role = {}
        this.role.status = '1'
        this.role.readonly = '0'
        this.outerVisible = false
        this.page()
      })
      this.$message({
        type: 'success',
        message: '修改成功!'
      })
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.addpud = true
      this.outerVisible = true
    },

    upd(val) {
      this.addpud = false
      this.outerVisible = true
      this.role = val
      this.role.status = val.status + ''
      this.role.readonly = val.readonly + ''
    },

    page() {
      if (this.value1 === null) {
        this.roleDto.create_time = ''
        this.roleDto.out_time = ''
      } else {
        if (this.value1.length > 0) {
          this.roleDto.create_time = this.value1[0]
          this.roleDto.out_time = this.value1[1]
        }
      }
      pageRole(this.roleDto).then(res => {
        this.Data = res.data.list
        this.total = res.data.total
      })

      //获取菜单数
      menuVos().then(ass => {
        console.log(ass.data)
        this.menuLists = ass.data
      })
    },

    //删除
    del(val) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'

      }).then(() => {
        delRole(val).then(as => {
          this.page()
        })
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    size(val) {
      this.roleDto.pageSize = val
      this.page()
    },

    curren(val) {
      this.roleDto.pageNum = val
      this.page()
    }

  }

}
</script>
